layui.use(['table'], function() {
var table = layui.table,
    $ = layui.jquery,
    layer = layui.layer,
    form = layui.form,
    laytpl = layui.laytpl,
    message = parent.message;;
var tableIns = table.render({
    elem: '#demo',
    height: 'full-132', //容器高度
    url: '../sys/role/list?_'+$.now(),
    where: {sidx: '', order: 'desc'},
    page: true,
    id: 'demo',
    limit: 20,
    cols: [
        [{
            checkbox: true,
            fixed: true
        }, {
            field: 'roleName',
            title: '角色名称',
            width: 300,
            sort: true
        }, {
            field: 'remark',
            title: '备注',
            width: 400
        }, {
            field: 'createTime',
            title: '创建时间',
            width: 350,
            sort: true
        },{
            fixed: 'right',
            title: '操作',
            width: 300,
            align: 'center',
            toolbar: '#barDemo'
        }]
    ],
    done: function(res, curr, count) {
    	
    },
    loading: true,
});
//监听搜索表单提交
form.on('submit(search)', function(data) {
    //带条件查询
    tableIns.reload({
    	where: {
    		sidx: '', order: 'desc',
    		roleName: data.field.roleName
    	}
    });
    return false;
});
//监听工具条
table.on('tool(demo)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
    var data = obj.data; //获得当前行数据
    var layEvent = obj.event; //获得 lay-event 对应的值
    var tr = obj.tr; //获得当前行 tr 的DOM对象

    if (layEvent === 'del') { //删除
        layer.confirm('确定删除该数据', function(index) {
            layer.close(index);
            //向服务端发送删除指令
            var roleIds = Array();
            roleIds.push(data.roleId);
            $.ajax({
        		type: "POST",
        	    url: "../sys/role/delete",
        	    data: JSON.stringify(roleIds),
        	    dataType: 'JSON',
        	    contentType: 'application/json',
        	    success: function(res){
        	    	if (res.code==0) {
        	        	parent.message.show({
        	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
        	                msg:'操作成功'//提示信息
        	            });
        	        	obj.del(); //删除对应行（tr）的DOM结构
        	        	//tableIns.reload({where: {sidx: '', order: 'desc'}});
        	        } else {
        	        	layer.msg(res.msg, {icon: 2});
        	        }
        		}
        	});
        });
    } else if (layEvent === 'edit') { //编辑
    	$.get("../sys/role/info/"+data.roleId, function(res){
			if(res.code==0){
				var d = {
		            role: res.role
		        };
		        laytpl($('#edit-tpl').html()).render(d, function(html) {
		        	var myheight;
		        	if($("body").height()>600){
		        		myheight=600;
		        	}
		        	else{
		        		myheight=$("body").height();
		        	}
		            layer.open({
		                type: 1,
		                title: '修改角色信息',
		                content: html,
		                skin: 'layui-layer-rim', //加上边框
		                area: ['450px','400px'],
		                btn: ['提交', '取消'],
		                yes: function(index, layero) {
		                    editIndex = index;
		                    $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
		                },
		                btn2: function(index, layero) {
		                	editIndex=index;
		                	editIndex && layer.close(editIndex);
		                    $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
		                    return false;
		                },
		                success: function() {
		                	getMenuTree(res.role)
		                    form.render(null, 'form-edit');
		                }
		            });
		        });
			}else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		});
    }
});
form.render(null, 'kit-search-form');
$('#kit-search-more').on('click', function() {
    $('.kit-search-mored').toggle();
});

var editIndex;
form.on('submit(formEdit)', function(data) {
	saveOrUpdate(data.field);
	editIndex && layer.close(editIndex); //关闭弹出层
    return false;
});

$('.kit-search-btns').children('a').off('click').on('click', function() {
    var $that = $(this),
    action = $that.data('action');
    switch (action) {
        case 'add':
            var d = {
                role: {
                	roleId: '',
                	roleName: '',
                	remark: ''
                }
            };
            //渲染
            laytpl($('#edit-tpl').html()).render(d,
                function(html) {
                    layer.open({
                        type: 1,
                        title: '新增角色',
                        content: html,
                        skin: 'layui-layer-rim', //加上边框
                        maxmin: true,
                        area: ['450px', '400px'],
                        btn: ['提交', '取消'],
                        yes: function(index, layero) {
                            editIndex = index;
                            $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
                        },
                        btn2: function(index, layero) {
                        	editIndex=index;
		                	editIndex && layer.close(editIndex);
                            $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
                            return false;
                        },
                        success: function() {
                        	getMenuTree(null);
                            form.render(null, 'form-edit');
                        }
                    });
                });
            break;
        case 'del-bulk':
            var d = table.checkStatus('demo');
            if (d.data.length === 0) {
                layer.msg('请选择要删除的数据');
                return;
            }
            var data = d.data,
                ids = [];
            layui.each(data, function(index, item) {
                ids.push(item.roleId);
            });
            layer.confirm('确定删除选中的数据', function(index) {
                layer.close(index);
                //向服务端发送删除指令
                $.ajax({
            		type: "POST",
            	    url: "../sys/role/delete",
            	    data: JSON.stringify(ids),
            	    dataType: 'JSON',
            	    contentType: 'application/json',
            	    success: function(res){
            	    	if (res.code==0) {
            	        	parent.message.show({
            	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
            	                msg:'操作成功'//提示信息
            	            });
            	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
            	        } else {
            	        	layer.msg(res.msg, {icon: 2});
            	        }
            		}
            	});
            });
            break;
        }
    });

saveOrUpdate = function (datas) {
	//获取选择的菜单
	var nodes = ztree.getCheckedNodes(true);
	var menuIdList = new Array();
	for(var i=0; i<nodes.length; i++) {
		menuIdList.push(nodes[i].menuId);
	}
	datas.menuIdList = menuIdList;
	
	var url = datas.roleId == null ? "../sys/role/save" : "../sys/role/update";
	$.ajax({
		type: "POST",
		url: url,
	    data: JSON.stringify(datas),
	    dataType: 'JSON',
	    contentType: 'application/json',
	    success: function(res){
	    	if (res.code==0) {
	        	message.show({
	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
	                msg:'操作成功'//提示信息
	            });
	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
	        } else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		}
	});
}

var setting = {
	data: {
		simpleData: {
			enable: true,
			idKey: "menuId",
			pIdKey: "parentId",
			rootPId: -1
		},
		key: {
			url:"nourl"
		}
	},
	check:{
		enable:true,
		nocheckInherit:true
	}
};

var ztree;

var getMenuTree = function(role) {
	//加载菜单树
	$.get("../sys/menu/perms", function(res){
		ztree = $.fn.zTree.init($("#menuTree"), setting, res.menuList);
		//展开所有节点
		ztree.expandAll(true);
		if(role!=null){
			//勾选角色所拥有的菜单
			var menuIds = role.menuIdList;
			for(var i=0; i<menuIds.length; i++) {
				var node = ztree.getNodeByParam("menuId", menuIds[i]);
				ztree.checkNode(node, true, false);
			}
		}
	});
}

});